package com.zyb.system.user.service.impl;

import com.zyb.constans.BaseConstants;
import com.zyb.system.login.domain.PhoneRegister;
import com.zyb.system.logininfo.domain.Logininfo;
import com.zyb.system.logininfo.service.impl.LogininfoServiceImpl;
import com.zyb.system.user.domain.User;
import com.zyb.system.user.mapper.UserMapper;
import com.zyb.system.user.service.IUserService;
import com.zyb.base.service.impl.BaseServiceImpl;
import com.zyb.utils.MD5Utils;
import com.zyb.utils.StrUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Arvin
 * @since 2023-01-31
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoServiceImpl logininfoService;
    @Override
    public User queryByPhone(String phone) {
        return userMapper.loadByPhone(phone);
    }

    @Override
    public void add(PhoneRegister register) {
        User user = new User();
        //补充数据
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //盐值加密
        String saltPassword = MD5Utils.encrypByMd5(salt + register.getPassword());
        user.setPassword(saltPassword);
        user.setCreatetime(new Date());
        user.setUsername(register.getPhone());
        user.setPhone(register.getPhone());
        user.setState(BaseConstants.User.STATE_NORMAL);
        userMapper.save(user);
        Logininfo logininfo = new Logininfo();
        //复制数据
        BeanUtils.copyProperties(user,logininfo);
        //设置状态
        logininfo.setType(BaseConstants.Logininfo.STATE_USER);
        logininfo.setDisable(BaseConstants.Logininfo.DISABLE_1);
        //保存数据
        logininfoService.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        //保存数据
        userMapper.update(user);

    }
}
